package cn.edu.hzw.criminalintent.fragmnet

import android.app.DatePickerDialog
import android.app.Dialog
import android.os.Bundle
import android.widget.DatePicker
import androidx.fragment.app.DialogFragment
import java.util.*

private const val ARG_DATE = "date"
class DatePickerFragment:DialogFragment() {
    /**
     * 对话框
     */
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        /**
         * 发回日期
         */
        val dateListener = DatePickerDialog.OnDateSetListener{
            _:DatePicker,
            year:Int,month:Int,day:Int ->
                val resultDate:Date = GregorianCalendar(year,month,day).time
            targetFragment?.let {
                fragment ->
                    (fragment as Callbacks).onDateSelected(resultDate)
            }
        }
        val date = arguments?.getSerializable(ARG_DATE) as Date
        val calendar = Calendar.getInstance()
        calendar.time = date
        val initialYear = calendar.get(Calendar.YEAR)
        val initialMonth = calendar.get(Calendar.MONTH)
        val initialDay = calendar.get(Calendar.DAY_OF_MONTH)
        return DatePickerDialog(
            /**
             * 获取视图的context对象
             */
            requireContext(),
            /**
             * 日期监听器
             */
            dateListener,
            /**
             * 年
             */
            initialYear,
            /**
             * 月
             */
            initialMonth,
            /**
             * 日
             */
            initialDay
        )
    }

    /**
     * 创建和设置fragment argument
     */
    companion object{
        fun newInstance(date: Date):
                DatePickerFragment{
            val args = Bundle().apply {
                putSerializable(ARG_DATE,date)
            }
            return DatePickerFragment().apply {
                arguments = args
            }
        }
    }

    /**
     * 创建回调接口
     */
    interface Callbacks{
        fun onDateSelected(date: Date)
    }
}